<template>
	<view class="cart-page">
		<!-- 顶部导航栏（原生view实现） -->
		<view class="top-bar">
			<view class="select-all">
				<!-- 原生checkbox -->
				<checkbox :checked="allSelected" @change="handleAllCheck" color="#e53e3e" class="checkbox"></checkbox>
				<text class="select-all-text">全选</text>
			</view>
			<view class="clear-btn" @click="clearCart">清空</view>
		</view>

		<!-- 主内容区域（原生scroll-view，无第三方滚动组件） -->
		<scroll-view class="main-content" scroll-y>
			<view class="cart-content">
				<!-- 空购物车状态 -->
				<view v-if="isEmpty && !loading" class="empty-cart">
					<!-- 原生image，无第三方依赖 -->
					<image src="/static/images/empty-cart.png" mode="widthFix" class="empty-img"
						@error="handleImgError('empty')"></image>
					<text class="empty-text">购物车还是空的~</text>
					<!-- 原生button -->
					<button class="go-shopping" @click="goToGoods">去逛逛</button>
				</view>

				<!-- 购物车列表 -->
				<view v-else-if="!loading" class="cart-list">
					<!-- 店铺分组 -->
					<view v-for="(store, storeIndex) in groupedCart" :key="store.storeId" class="store-group">
						<view class="store-header">
							<checkbox :checked="store.allSelected" @change="handleStoreCheck(storeIndex)"
								color="#e53e3e" class="checkbox"></checkbox>
							<text class="store-name">{{ store.storeName }}</text>
						</view>

						<!-- 商品列表 -->
						<view class="goods-list">
							<view v-for="(item, itemIndex) in store.goodsList" :key="item.id" class="cart-item">
								<checkbox :checked="item.isChecked" @change="handleItemCheck(storeIndex, itemIndex)"
									color="#e53e3e" class="item-checkbox"></checkbox>

								<!-- 原生image，无第三方依赖 -->
								<image :src="handleImgURL(item.goodsImg)" mode="widthFix" class="goods-img" lazy-load
									@error="handleImgError('goods', storeIndex, itemIndex)"></image>

								<view class="goods-info">
									<text class="goods-name">{{ item.goodsName }}</text>
									<text class="goods-price">¥{{ item.goodsPrice.toFixed(2) }}</text>
								</view>

								<view class="count-control">
									<view class="count-btn" @click="decreaseCount(storeIndex, itemIndex)"
										:class="{ disabled: item.count <= 1 }">-</view>
									<text class="count-num">{{ item.count }}</text>
									<view class="count-btn" @click="increaseCount(storeIndex, itemIndex)"
										:class="{ disabled: item.count >= 99 }">+</view>
								</view>

								<view class="delete-btn" @click="deleteItem(storeIndex, itemIndex)">删除</view>
							</view>
						</view>
					</view>
				</view>

				<!-- 加载动画（原生view实现） -->
				<view v-if="loading" class="loading-container">
					<view class="loading-spinner"></view>
				</view>
			</view>
		</scroll-view>

		<!-- 底部结算栏（原生view+button） -->
		<view v-if="!isEmpty && !loading" class="cart-footer">
			<view class="footer-left">
				<text class="selected-info">已选 {{ selectedGoodsCount }} 件，总价</text>
				<text class="total-price">¥{{ totalPrice.toFixed(2) }}</text>
			</view>
			<button class="checkout-btn" @click="goToCheckout" :disabled="selectedGoodsCount === 0">
				去结算
			</button>
		</view>
	</view>
</template>

<script>
	// 仅引入API和配置，无任何第三方组件
	import {
		baseUrl
	} from '@/utils/config.js'
	import {
		getMyList,
		deleteByIds,
		update,
		deleteAllByMy,
		updateIsCheckedAllByMy,
		listIsCheckedByMy
	} from '@/api/cart.js'

	// 请求封装（仅用Uniapp原生uni.request）
	const requestWithToken = async (apiFunc, params = {}) => {
		// 确保apiFunc是基于uni.request的原生请求
		return apiFunc({
			...params,
			header: {
				'Content-Type': 'application/json',
				// 如有token，用uni.getStorageSync获取（原生方式）
				'token': uni.getStorageSync('token') || '',
				...params.header
			}
		})
	}

	export default {
		data() {
			return {
				cartList: [],
				groupedCart: [],
				loading: true,
				isEmpty: false,
				selectedGoodsCount: 0,
				totalPrice: 0,
				allSelected: false,
			};
		},

		// 关键：如果必须用KeepAlive，添加延迟加载（确保DOM渲染完成）
		activated() {
			// 用$nextTick确保DOM渲染，再延迟100ms（兼容慢渲染场景）
			this.$nextTick(() => {
				setTimeout(() => {
					this.loadCartData();
				}, 100);
			});
		},

		onShow() {
			// 非KeepAlive场景，直接加载
			this.loadCartData();
		},

		methods: {
			// 处理图片URL（原生字符串处理）
			handleImgURL(url) {
				if (!url) return '/static/images/default-goods.png';
				return url.includes('http') ? url : `${baseUrl}${url}`;
			},

			// 图片加载失败（修复核心：使用UniApp原生选择器回调获取节点）
			handleImgError(type, storeIndex, itemIndex) {
				if (type === 'empty') {
					// 空购物车图片错误：直接通过选择器获取单个节点
					uni.createSelectorQuery().in(this)
						.select('.empty-img')
						.fields({
							node: true
						}, (res) => {
							if (res.node) {
								res.node.src = '/static/images/default-empty.png'; // 备用空购物车图
							}
						})
						.exec();
				} else if (type === 'goods') {
					// 商品图片错误：通过层级选择器精准定位当前错误图片（避免批量修改）
					const selector =
						`.store-group:nth-child(${storeIndex + 1}) .cart-item:nth-child(${itemIndex + 1}) .goods-img`;
					uni.createSelectorQuery().in(this)
						.select(selector)
						.fields({
							node: true
						}, (res) => {
							if (res.node) {
								res.node.src = '/static/images/default-goods.png'; // 商品备用图
							}
						})
						.exec();
				}
			},

			// 加载购物车数据（原生异步请求）
			async loadCartData() {
				this.loading = true;
				try {
					const res = await requestWithToken(getMyList);
					if (!res) throw new Error('获取购物车数据失败：服务器未返回有效响应');

					if ([200, 0].includes(res.code) && res.data) {
						this.cartList = res.data || [];
						this.groupCartByStore();
					} else {
						throw new Error(res.msg || `获取购物车数据失败，错误码: ${res.code}`);
					}
				} catch (e) {
					console.error('加载购物车失败:', e);
					uni.showToast({
						title: e.message || '加载购物车失败，请稍后重试',
						icon: 'none',
						duration: 2000
					});
					this.cartList = [];
					this.groupedCart = [];
				} finally {
					this.loading = false;
					this.updateCartStatus();
				}
			},

			// 分组购物车（纯数据处理，无DOM操作）
			groupCartByStore() {
				const storeMap = {};
				this.cartList.forEach(item => {
					const safeItem = {
						...item,
						isChecked: item.isChecked === 1,
						count: Math.max(1, Math.min(99, item.count || 1))
					};

					const storeId = safeItem.storeId || 'default';
					if (!storeMap[storeId]) {
						storeMap[storeId] = {
							storeId,
							storeName: safeItem.storeName || '未知店铺',
							goodsList: [],
							allSelected: false
						};
					}
					storeMap[storeId].goodsList.push(safeItem);
				});
				this.groupedCart = Object.values(storeMap);
				this.syncStoreSelection();
			},

			// 同步店铺选择状态（纯数据处理）
			syncStoreSelection() {
				this.groupedCart.forEach(store => {
					store.allSelected = store.goodsList.length > 0 && store.goodsList.every(item => item
					.isChecked);
				});
				const hasGoods = this.groupedCart.some(store => store.goodsList.length > 0);
				this.allSelected = hasGoods && this.groupedCart.every(store => store.allSelected);
			},

			// 更新购物车状态（纯数据处理）
			updateCartStatus() {
				this.isEmpty = this.groupedCart.length === 0 || this.groupedCart.every(store => store.goodsList.length ===
					0);
				if (this.isEmpty) {
					this.selectedGoodsCount = 0;
					this.totalPrice = 0;
					return;
				}

				let count = 0;
				let price = 0;
				this.groupedCart.forEach(store => {
					store.goodsList.forEach(item => {
						if (item.isChecked) {
							count += item.count;
							price += Number(item.goodsPrice) * item.count;
						}
					});
				});
				this.selectedGoodsCount = count;
				this.totalPrice = price;
				this.syncStoreSelection();
			},

			// 全选（原生事件处理）
			async handleAllCheck(e) {
				const isChecked = e.detail.checked;
				try {
					await requestWithToken(updateIsCheckedAllByMy, {
						data: {
							isChecked: isChecked ? 1 : 0
						}
					});
					this.groupedCart.forEach(store => {
						store.allSelected = isChecked;
						store.goodsList.forEach(item => item.isChecked = isChecked);
					});
					this.allSelected = isChecked;
					this.updateCartStatus();
				} catch (e) {
					console.error('更新全选状态失败:', e);
					uni.showToast({
						title: e.message || '操作失败',
						icon: 'none'
					});
				}
			},

			// 店铺选择（原生事件处理）
			async handleStoreCheck(storeIndex) {
				const store = this.groupedCart[storeIndex];
				const newStatus = !store.allSelected;
				try {
					const updatePromises = store.goodsList.map(item =>
						requestWithToken(update, {
							data: {
								id: item.id,
								isChecked: newStatus ? 1 : 0
							}
						})
					);
					await Promise.all(updatePromises);
					store.allSelected = newStatus;
					store.goodsList.forEach(item => item.isChecked = newStatus);
					this.syncStoreSelection();
					this.updateCartStatus();
				} catch (e) {
					console.error('更新店铺选择状态失败:', e);
					uni.showToast({
						title: e.message || '操作失败',
						icon: 'none'
					});
				}
			},

			// 商品选择（原生事件处理）
			async handleItemCheck(storeIndex, itemIndex) {
				const store = this.groupedCart[storeIndex];
				const item = store.goodsList[itemIndex];
				const newStatus = !item.isChecked;
				try {
					await requestWithToken(update, {
						data: {
							id: item.id,
							isChecked: newStatus ? 1 : 0
						}
					});
					item.isChecked = newStatus;
					store.allSelected = store.goodsList.every(goods => goods.isChecked);
					this.syncStoreSelection();
					this.updateCartStatus();
				} catch (e) {
					console.error('更新商品选择状态失败:', e);
					uni.showToast({
						title: e.message || '操作失败',
						icon: 'none'
					});
				}
			},

			// 减少数量（原生事件处理）
			async decreaseCount(storeIndex, itemIndex) {
				const store = this.groupedCart[storeIndex];
				const item = store.goodsList[itemIndex];
				if (item.count <= 1) return;

				try {
					const newCount = item.count - 1;
					await requestWithToken(update, {
						data: {
							id: item.id,
							count: newCount
						}
					});
					item.count = newCount;
					this.updateCartStatus();
				} catch (e) {
					console.error('减少商品数量失败:', e);
					uni.showToast({
						title: e.message || '操作失败',
						icon: 'none'
					});
				}
			},

			// 增加数量（原生事件处理）
			async increaseCount(storeIndex, itemIndex) {
				const store = this.groupedCart[storeIndex];
				const item = store.goodsList[itemIndex];
				if (item.count >= 99) {
					uni.showToast({
						title: '商品数量不能超过99',
						icon: 'none',
						duration: 2000
					});
					return;
				}

				try {
					const newCount = item.count + 1;
					await requestWithToken(update, {
						data: {
							id: item.id,
							count: newCount
						}
					});
					item.count = newCount;
					this.updateCartStatus();
				} catch (e) {
					console.error('增加商品数量失败:', e);
					uni.showToast({
						title: e.message || '操作失败',
						icon: 'none'
					});
				}
			},

			// 删除商品（原生事件处理）
			async deleteItem(storeIndex, itemIndex) {
				const store = this.groupedCart[storeIndex];
				const item = store.goodsList[itemIndex];
				// 原生弹窗
				uni.showModal({
					title: '提示',
					content: '确定要删除该商品吗？',
					cancelText: '取消',
					confirmText: '确定',
					success: async (res) => {
						if (res.confirm) {
							try {
								await requestWithToken(deleteByIds, {
									data: {
										ids: [item.id]
									}
								});
								store.goodsList.splice(itemIndex, 1);
								if (store.goodsList.length === 0) this.groupedCart.splice(storeIndex, 1);
								this.updateCartStatus();
								uni.showToast({
									title: '删除成功',
									icon: 'success',
									duration: 1500
								});
							} catch (e) {
								console.error('删除商品失败:', e);
								uni.showToast({
									title: e.message || '删除失败',
									icon: 'none'
								});
							}
						}
					}
				});
			},

			// 清空购物车（原生事件处理）
			async clearCart() {
				if (this.isEmpty) {
					uni.showToast({
						title: '购物车已为空',
						icon: 'none',
						duration: 2000
					});
					return;
				}

				uni.showModal({
					title: '警告',
					content: '确定要清空整个购物车吗？',
					cancelText: '取消',
					confirmText: '确定',
					success: async (res) => {
						if (res.confirm) {
							try {
								await requestWithToken(deleteAllByMy);
								this.cartList = [];
								this.groupedCart = [];
								this.updateCartStatus();
								uni.showToast({
									title: '购物车已清空',
									icon: 'success',
									duration: 1500
								});
							} catch (e) {
								console.error('清空购物车失败:', e);
								uni.showToast({
									title: e.message || '操作失败',
									icon: 'none'
								});
							}
						}
					}
				});
			},

			// 去逛逛（原生路由跳转）
			goToGoods() {
				uni.switchTab({
					url: '/pages/goods/store'
				});
			},

			// 去结算（原生路由跳转）
			async goToCheckout() {
				if (this.selectedGoodsCount === 0) {
					uni.showToast({
						title: '请选择要结算的商品',
						icon: 'none',
						duration: 2000
					});
					return;
				}

				try {
					const res = await requestWithToken(listIsCheckedByMy);
					if (!res) throw new Error('获取选中商品失败：服务器未返回有效响应');

					if ([200, 0].includes(res.code) && res.data) {
						const formattedGoods = res.data.map(goods => ({
							...goods,
							isChecked: goods.isChecked === 1
						}));
						uni.navigateTo({
							url: `/pages/order/confirmOrder?cartGoods=${encodeURIComponent(JSON.stringify(formattedGoods))}`,
							fail: (err) => {
								console.error('跳转结算页失败:', err);
								uni.showToast({
									title: '结算页面不存在',
									icon: 'none',
									duration: 2000
								});
							}
						});
					} else {
						throw new Error(res.msg || '获取选中商品失败');
					}
				} catch (e) {
					console.error('结算失败:', e);
					uni.showToast({
						title: e.message,
						icon: 'none'
					});
				}
			}
		}
	};
</script>

<style scoped>
	/* 所有样式均为原生CSS，无第三方样式依赖 */
	.cart-page {
		min-height: 100vh;
		background-color: #f5f5f5;
		padding-top: var(--status-bar-height);
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
	}

	.top-bar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15rpx 20rpx;
		background-color: #fff;
	}

	.select-all {
		display: flex;
		align-items: center;
	}

	.checkbox {
		transform: scale(0.8);
		margin-right: 8rpx;
	}

	.select-all-text {
		font-size: 14px;
		color: #333;
	}

	.clear-btn {
		font-size: 14px;
		color: #e53e3e;
	}

	.main-content {
		flex: 1;
		height: 0;
	}

	.cart-content {
		padding-bottom: 100rpx;
	}

	.empty-cart {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-top: 100rpx;
	}

	.empty-img {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 30rpx;
		background-color: #f5f5f5;
	}

	.empty-text {
		color: #999;
		font-size: 14px;
		margin-bottom: 30rpx;
	}

	.go-shopping {
		background-color: #e53e3e;
		color: #fff;
		border-radius: 40rpx;
		padding: 15rpx 40rpx;
		font-size: 14px;
	}

	.cart-list {
		background-color: #f5f5f5;
	}

	.store-group {
		background-color: #fff;
		margin-bottom: 10rpx;
	}

	.store-header {
		display: flex;
		align-items: center;
		padding: 15rpx 20rpx;
		border-bottom: 1px solid #f5f5f5;
	}

	.store-name {
		font-size: 14px;
		color: #333;
		flex: 1;
	}

	.goods-list {
		padding: 0 20rpx;
	}

	.cart-item {
		display: flex;
		align-items: center;
		padding: 15rpx 0;
		border-bottom: 1px solid #f5f5f5;
	}

	.item-checkbox {
		transform: scale(0.8);
		margin-right: 15rpx;
	}

	.goods-img {
		width: 120rpx;
		height: 120rpx;
		border-radius: 8rpx;
		background-color: #f5f5f5;
	}

	.goods-info {
		flex: 1;
		margin: 0 15rpx;
	}

	.goods-name {
		font-size: 14px;
		color: #333;
		line-height: 1.4;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
	}

	.goods-price {
		font-size: 16px;
		color: #e53e3e;
		font-weight: bold;
		margin-top: 10rpx;
		display: block;
	}

	.count-control {
		display: flex;
		align-items: center;
		width: 150rpx;
	}

	.count-btn {
		width: 40rpx;
		height: 40rpx;
		line-height: 40rpx;
		text-align: center;
		border: 1px solid #ddd;
		border-radius: 4rpx;
		font-size: 16px;
	}

	.count-btn.disabled {
		color: #ccc;
		border-color: #eee;
	}

	.count-num {
		width: 70rpx;
		text-align: center;
		font-size: 14px;
	}

	.delete-btn {
		font-size: 14px;
		color: #999;
		margin-left: 10rpx;
	}

	.cart-footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		background-color: #fff;
		padding: 0 20rpx;
		border-top: 1px solid #f5f5f5;
	}

	.footer-left {
		display: flex;
		align-items: baseline;
	}

	.selected-info {
		font-size: 14px;
		color: #666;
	}

	.total-price {
		font-size: 18px;
		color: #e53e3e;
		font-weight: bold;
		margin-left: 10rpx;
	}

	.checkout-btn {
		width: 200rpx;
		height: 70rpx;
		line-height: 70rpx;
		background-color: #e53e3e;
		color: #fff;
		border-radius: 35rpx;
		font-size: 16px;
		text-align: center;
	}

	.checkout-btn:disabled {
		background-color: #f59f9f;
	}

	.loading-container {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 50rpx 0;
	}

	.loading-spinner {
		width: 40rpx;
		height: 40rpx;
		border: 4rpx solid #f3f3f3;
		border-top: 4rpx solid #e53e3e;
		border-radius: 50%;
		animation: spin 1s linear infinite;
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}

	/* 清除原生button默认样式 */
	button::after {
		border: none;
	}
</style>